package serial_handle

import (
	"data-system/models"
	"fmt"
)

type SerialHandler interface {
	Encode() (models.SerialHandleCtx, error)
	Decode() (models.SerialHandleCtx, error)
}

type handlerFunc func(ctx models.SerialHandleCtx) (SerialHandler, error)

var handlers = map[string]handlerFunc{
	"string": NewSerialStringCtx,
	"number": NewSerialNumberCtx,
	"json":   NewSerialJsonArr1Ctx,
}

func Router(ctx models.SerialHandleCtx) (SerialHandler, error) {
	key := ctx.Column.NodeType + "_" + ctx.Column.Name
	method, ok := handlers[key]
	if !ok {
		method, ok = handlers[ctx.Column.Type]
	}
	if ok {
		handler, err := method(ctx)
		if err != nil {
			return nil, err
		}
		return handler, nil
	} else {
		return nil, fmt.Errorf("【%v - %v - %v】没有对应的处理器，请联系开发人员", ctx.Column.NodeType, ctx.Column.Name, ctx.Column.Type)
	}
}
